package com.example.dilidili_ting.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.dilidili_ting.R;
import com.example.dilidili_ting.bean.DataBeanTing;
import com.example.dilidili_ting.utils.OkhttpUtilsTing;
import com.example.dilidili_ting.utils.SharedPreferencesUtilsTing;
import com.example.dilidili_ting.bean.loginResultBeanTing;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.thecode.aestheticdialogs.AestheticDialog;
import com.thecode.aestheticdialogs.DialogStyle;
import com.thecode.aestheticdialogs.DialogType;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class loginActivityTing extends AppCompatActivity {

    private ImageView ivBack2Ting;
    private TextView titleBarNameTing;
    private ImageView ivXiaokeaiTing;
    private EditText etUsernameTing;
    private EditText etPasswordTing;
    private TextView tvFindPasswordTing;
    private Button loginBtnTing;
    private TextView tvRegisterTing;
    //账号、密码的获取值
    private String userName_ting,psw_ting,spPsw_ting;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_ting);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        initView();
    }

    private void initView() {
        etUsernameTing = (EditText) findViewById(R.id.et_username_ting);
        etPasswordTing = (EditText) findViewById(R.id.et_password_ting);
        tvFindPasswordTing = (TextView) findViewById(R.id.tv_find_password_ting);
        loginBtnTing = (Button) findViewById(R.id.login_btn_ting);
        tvRegisterTing = (TextView) findViewById(R.id.tv_register_ting);
        ivBack2Ting = (ImageView) findViewById(R.id.iv_back2_ting);
        titleBarNameTing = (TextView) findViewById(R.id.title_bar_name_ting);
        titleBarNameTing.setText("登陆账号");
        ivXiaokeaiTing = (ImageView) findViewById(R.id.iv_xiaokeai_ting);
        ivBack2Ting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginActivityTing.this.finish();
            }
        });

        //立即注册控件的点击事件
        tvRegisterTing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO:跳转到注册页面，并要求注册页面传回注册用户名
                Intent intent=new Intent(loginActivityTing.this, regActivityTing.class);
                startActivityForResult(intent,1);
            }
        });
        //找回密码控件的点击事件
        tvFindPasswordTing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转找回密码页面（后续实现）
                //TODO:跳转到找回密码
                Intent i = new Intent(loginActivityTing.this, FindPswActivityTing.class);
                startActivityForResult(i,1);
            }
        });
        //登录按钮的点击事件
        loginBtnTing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_click();
            }
        });
    }

    //获取注册页面返回的结果
    @Override
    protected void onActivityResult(int requestCode,int resultCode,Intent data){
        super.onActivityResult(requestCode,resultCode,data);
//        System.out.println(data);
        if (data!=null){
            //从注册界面传递过来的用户名和密码
            String userName=data.getStringExtra("userName");
            String password=data.getStringExtra("password");
            if (!TextUtils.isEmpty(userName)){
                etUsernameTing.setText(userName);
                etPasswordTing.setText(password);
                //设置光标的位置
                etUsernameTing.setSelection(userName.length());
                etPasswordTing.setSelection(password.length());
            }
        }
    }

    //获取用户输入的用户和密码
    private  void getEditString(){
        userName_ting=etUsernameTing.getText().toString().trim();
        psw_ting=etPasswordTing.getText().toString().trim();
    }

    /**实现登录功能
     */
    private void btn_click(){
        getEditString();
        spPsw_ting= SharedPreferencesUtilsTing.readPsw(loginActivityTing.this,userName_ting);
        if (TextUtils.isEmpty(userName_ting)){
            new AestheticDialog.Builder(this, DialogStyle.TOASTER, DialogType.WARNING)
                    .setTitle("WARNING")
                    .setMessage("请输入用户名")
                    .setDuration(1500)
                    .show();
            return;
        }else if (TextUtils.isEmpty(psw_ting)){
            new AestheticDialog.Builder(this, DialogStyle.TOASTER, DialogType.WARNING)
                    .setTitle("WARNING")
                    .setMessage("请输入密码")
                    .setDuration(1500)
                    .show();
            return;
        }else if ((spPsw_ting!=null&&!TextUtils.isEmpty(spPsw_ting)&&!psw_ting.equals(spPsw_ting))){
            new AestheticDialog.Builder(this, DialogStyle.TOASTER, DialogType.ERROR)
                    .setTitle("ERROR")
                    .setMessage("输入的用户名与密码不一致")
                    .setDuration(1500)
                    .show();
            return;
        }else{
            JsonObject jo = new JsonObject();
            jo.addProperty("userName",userName_ting);
            jo.addProperty("pwd",psw_ting);
//            jo.addProperty("kfz","zxt");
            OkhttpUtilsTing.isPOST("AndroidUser/login", false, jo, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {}

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res = response.body().string();
                    Gson gson = new Gson();
                    final DataBeanTing<String> r = gson.fromJson(res, DataBeanTing.class);
                    loginActivityTing.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(r.code == 200){
                                //把账号、密码和账号标识保存到sp里面
                                new AestheticDialog.Builder(loginActivityTing.this, DialogStyle.EMOTION, DialogType.SUCCESS)
                                        .setTitle("SUCCESS")
                                        .setMessage("登录成功")
                                        .setDuration(2000)
                                        .show();
                                SharedPreferencesUtilsTing.saveRegisterInfo(loginActivityTing.this,userName_ting,psw_ting);
                                SharedPreferencesUtilsTing.saveLoginStatus(loginActivityTing.this,true,userName_ting);
                                SharedPreferencesUtilsTing.saveUserId(loginActivityTing.this,r.data);
                                Log.i("userid",gson.toJson(r));
                                //设置跳转时长
                                Timer timer=new Timer();
                                TimerTask task=new TimerTask() {
                                    @Override
                                    public void run() {
                                        Intent data=new Intent();
                                        data.putExtra("isLogin",true);
                                        setResult(RESULT_OK,data);
                                        loginActivityTing.this.finish();
                                    }
                                };
                                timer.schedule(task,2000);
                            }else {
                                new AestheticDialog.Builder(loginActivityTing.this, DialogStyle.EMOTION, DialogType.ERROR)
                                        .setTitle("ERROR")
                                        .setMessage(r.msg)
                                        .setDuration(1500)
                                        .show();
                            }
                        }
                    });
                }
            });
        }
    }

}